#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:吹神
@file:remove_report.py
@time:2021/04/05
"""

import json
import os
import shutil

from config.settings import BASE_PATH, REPORT_PATH
from time import time

# 生成html报告路径
ALLURE_PLUS_DIR = str(BASE_PATH.joinpath("report", "html"))


def get_dirname():
    """
    写入history.json文件
    :return:
    """
    hostory_file = os.path.join(REPORT_PATH, "history.json")
    if os.path.exists(hostory_file):
        with open(hostory_file, encoding="utf-8") as f:
            # 去除字符串空格字符
            data = f.read().replace(" ", "")
            li = eval(data)
        # 根据构建次数进行排序，从大到小
        li.sort(key=lambda x: x['buildOrder'], reverse=True)
        # 返回下一次的构建次数，所以要在排序后的历史数据中的buildOrder+1
        return li[0]["buildOrder"] + 1, li
    else:
        # 首次进行生成报告，肯定会进到这一步，先创建history.json,然后返回构建次数1（代表首次）
        with open(hostory_file, "w") as f:
            pass
        return 1, None


def update_trend_data(dirname, old_data: list):
    """
    dirname：构建次数
    old_data：备份的数据
    update_trend_data(get_dirname())
    """
    # history-trend.json路径
    WIDGETS_DIR = os.path.join(ALLURE_PLUS_DIR, f"{str(dirname)}", "widgets")
    # 读取最新生成的history-trend.json数据
    with open(os.path.join(WIDGETS_DIR, "history-trend.json")) as f:
        data = f.read()

    new_data = json.loads(data)
    if old_data is not None:
        new_data[0]["buildOrder"] = old_data[0]["buildOrder"] + 1
    else:
        old_data = []
        new_data[0]["buildOrder"] = 1
    # 给最新生成的数据添加reportUrl key，reportUrl要根据自己的实际情况更改
    new_data[0]["reportUrl"] = os.path.join(ALLURE_PLUS_DIR, str(dirname), "index.html")
    # 把最新的数据，插入到备份数据列表首位
    old_data.insert(0, new_data[0])
    # 把所有生成的报告中的history-trend.json都更新成新备份的数据old_data，这样的话，点击历史趋势图就可以实现新老报告切换
    for i in range(1, dirname + 1):
        with open(os.path.join(ALLURE_PLUS_DIR, f"{str(i)}", "widgets", "history-trend.json"), "w+") as f:
            f.write(json.dumps(old_data))
    # 把数据备份到history.json
    hostory_file = os.path.join(REPORT_PATH, "history.json")
    with open(hostory_file, "w+") as f:
        f.write(json.dumps(old_data))
    return old_data, new_data[0]["reportUrl"]


def run():
    """
    生成测试报告
    :return:
    """
    number = str(int(time()))

    allure_path = os.path.join(REPORT_PATH, number)
    # 执行测试，并生成allure需要的数据
    command = f'pytest {BASE_PATH} -s  --alluredir={allure_path}'
    os.system(command)
    # 先调用get_dirname()，获取到这次需要构建的次数
    build_order, old_data = get_dirname()
    # 复制配置文件
    shutil.copy(os.path.join(REPORT_PATH, "environment.xml"), os.path.join(REPORT_PATH, number))
    shutil.copy(os.path.join(REPORT_PATH, "Categories.json"), os.path.join(REPORT_PATH, number))
    # 再执行命令行
    command = fr"D:\allure-2.13.9\bin\allure.bat generate {allure_path} -o {os.path.join(ALLURE_PLUS_DIR, str(build_order))} --clean"
    os.system(command)
    # 执行完毕后再调用update_trend_data()
    update_trend_data(build_order, old_data)

    # 执行完成，递归删除
    shutil.rmtree(os.path.join(REPORT_PATH, number))


def remove_html():
    """
    删除整个html下所有测试报告
    :return:
    """
    html_path = os.path.join(REPORT_PATH, "html")
    history_path = os.path.join(REPORT_PATH, "history.json")
    if os.path.exists(html_path):
        # 递归删除html下报告目录，
        shutil.rmtree(html_path)
    if os.path.isfile(history_path):
        # 删除history.json文件
        os.remove(history_path)
    # 创建html目录
    os.mkdir(html_path)



if __name__ == '__main__':
    # run()
    remove_html()